﻿using Lamex.Interface;
using Lamex.Library;
using Lamex.SystemManager.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Lamex.Base;
using Lamex.SystemManager.BLL;
using DevExpress.XtraEditors;
using DevExpress.Services.Internal;
using Lamex.Common;
using DevExpress.Utils.Menu;
using DevExpress.XtraGrid.Views.Grid;

namespace Lamex.SystemManager.UI
{
    public partial class frmMenu : frmBaseChild
    {
        public frmMenu()
        {
            InitializeComponent();
        }

        private void frmMenu_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            Init();
            
        }


        /// <summary>
        /// 绑定树形数据
        /// </summary>
        private void Init()
        {
            treeView1.Nodes.Clear();
            treeView1.BeginUpdate();
            Cursor.Current = Cursors.WaitCursor;

            //先获取系统类型，然后对不同的系统类型下的菜单进行绑定显示
           
           
                TreeNode pNode = new TreeNode();
                pNode.Text = "美时权限系统";//系统类型节点
                pNode.Name = "001";
                pNode.ImageIndex = 0;
                pNode.SelectedImageIndex = 0;
                this.treeView1.Nodes.Add(pNode);

                string systemType = "001";//系统标识ID

                //绑定树控件
                //一般情况下，对Ribbon样式而言，一级菜单表示RibbonPage；二级菜单表示PageGroup;三级菜单才是BarButtonItem最终的菜单项。
                List<MenuNodeInfo> menuList = BaseFactory<Sys_Menu>.Instance.GetTree( systemType ).ToList() ;
                foreach (MenuNodeInfo info in menuList)
                {
                    TreeNode item = new TreeNode();
                    item.Name = info.ID;
                    item.Text = info.Name;//一级菜单节点
                    item.Tag = info;//对菜单而言，记录其MenuNodeInfo到Tag中，作为判断依据
                    item.ImageIndex = 1;
                    item.SelectedImageIndex = 1;
                    pNode.Nodes.Add(item);

                    AddChildNode(info.Children, item);
                }
            

            Cursor.Current = Cursors.Default;
            treeView1.EndUpdate();
            //this.treeView1.ExpandAll();
        }

        private void AddChildNode(List<MenuNodeInfo> list, TreeNode fnode)
        {
            foreach (MenuNodeInfo info in list)
            {
                TreeNode item = new TreeNode();
                item.Name = info.ID;
                item.Text = info.Name;//二、三级菜单节点
                item.Tag = info;//对菜单而言，记录其MenuNodeInfo到Tag中，作为判断依据
                int index = (fnode.ImageIndex + 1 > 3) ? 3 : fnode.ImageIndex + 1;
                item.ImageIndex = index;
                item.SelectedImageIndex = index;
                fnode.Nodes.Add(item);

                AddChildNode(info.Children, item);
            }
        }

        public override void DoView(IButtonInfo sender)
        {
            string WhereSql = "";
            if (!string.IsNullOrEmpty(txtName.Text))
            {
                WhereSql += " and Name ='" + txtName.Text + "'";
            }
            if (!string.IsNullOrEmpty(txtWinformId.Text))
            {
                WhereSql += " and WinformId ='" + txtWinformId.Text + "'";
            }
            if (!string.IsNullOrEmpty(txtWinformType.Text))
            {
                WhereSql += " and WinformType ='" + txtWinformType.Text + "'";
            }
            if (txtEnabled.Checked)
            {
                WhereSql += " and Enabled ='" + txtEnabled.Checked + "'";
            }

            List<Sys_MenuInfo> lst = BaseFactory<Sys_Menu>.Instance.GetEntriyList(" 1 =1 " + WhereSql);
            
            gcView.DataSource = lst;
            gridView2.BestFitColumns();

        }

        public override void DoAdd(IButtonInfo sender)
        {
            
            frmMenuEdit frm = new frmMenuEdit("");
            frm.ShowDialog();
            base.DoAdd(sender);
        }

        public override void DoEdit(IButtonInfo sender)
        {
            if (gridView2.RowCount == 0) return;
            frmMenuEdit frm = new frmMenuEdit(id);
            frm.ShowDialog();
            base.DoAdd(sender);
            base.DoEdit(sender);
        }

        public override void DoDelete(IButtonInfo sender)
        {
            if (string.IsNullOrEmpty(id))
            {
                XtraMessageBox.Show("没有选中要删除的数据！");
                return;
            }
           if( BaseFactory<Sys_Menu>.Instance.Delete(id))
           {
               if (BaseFactory<Sys_Function>.Instance.ExecuteNonQuery(" DELETE  FROM dbo.Sys_Function  WHERE ID='"+id+"';DELETE  FROM dbo.Sys_Function  WHERE PID='"+id+"'")>0)
               {
                   XtraMessageBox.Show("删除成功！");
               }
               
               DoView(null);
           }
           else
           {
               XtraMessageBox.Show("删除失败！");
           }
            base.DoDelete(sender);
        }

        public override void DoExport(IButtonInfo sender)
        {
            
            try
            {
                SaveFileDialog dlg = new SaveFileDialog();
                //dlg.Filter = "PDF file(*.pdf)|*.pdf";
                dlg.Filter = "Excel文件(*.xls)|*.xls";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    //DXMenuItem item = sender as DXMenuItem;
                    //GridView view = (GridView)item.Tag;
                    //view.ExportToPdf(dlg.FileName);
                    gcView.ExportToXls(dlg.FileName);
                    DevExpress.XtraEditors.XtraMessageBox.Show("导出成功", "提示", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            base.DoExport(sender);
        }

        string id = "";
        private void gcView_Click(object sender, EventArgs e)
        {
            int i = gridView2.FocusedRowHandle;
            id = gridView2.GetRowCellDisplayText(i, "ID");
        }


        /// <summary>
        /// 实现树开型拖拽过功能;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            // 定义一个中间变量
            TreeNode treeNode;
            //判断拖动的是否为TreeNode类型，不是的话不予处理
            if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                // 拖放的目标节点
                TreeNode targetTreeNode;
                // 获取当前光标所处的坐标
                // 定义一个位置点的变量，保存当前光标所处的坐标点
                Point point = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                // 根据坐标点取得处于坐标点位置的节点
                targetTreeNode = ((TreeView)sender).GetNodeAt(point);
                // 获取被拖动的节点
                treeNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
                if (targetTreeNode.Name!=treeNode.Name)
                {
                    if (MessageBox.Show("是否将【"+treeNode.Text+"】移动到【"+targetTreeNode.Text+"】下面","提示" , MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        return;
                    Sys_FunctionInfo fun = BaseFactory<Sys_Function>.Instance.GetEntriyList(" 1=1 and ID='" + treeNode.Name + "' ").FirstOrDefault();
                    //BaseFactory<Sys_Menu>.Instance.ExecuteNonQuery("UPDATE Sys_Menu SET PID='" + targetTreeNode.Name + "' Where ID='" + treeNode.Name + "'");
                    if (BaseFactory<Sys_Menu>.Instance.ExecuteNonQuery("UPDATE Sys_Menu SET PID='" + targetTreeNode.Name + "' Where ID='" + treeNode.Name + "'") > 0)
                    {
                        if (BaseFactory<Sys_Menu>.Instance.ExecuteNonQuery("UPDATE Sys_Function SET PID='" + targetTreeNode.Name + "' Where ID='" + treeNode.Name + "'") > 0)
                        {
                            targetTreeNode.Nodes.Add((TreeNode)treeNode.Clone());
                            treeNode.Remove();
                            MessageBox.Show("成功移动！");
                        }

                    }
                    
                }
               
            }
        }

        private void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            // 拖动效果设成移动
            e.Effect = DragDropEffects.Move;
        }
        
        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            if (true)
            {
                // 开始进行拖放操作，并将拖放的效果设置成移动。
                this.DoDragDrop(e.Item, DragDropEffects.Move);
            }
        }

        private void ToolStripMenuRefresh_Click(object sender, EventArgs e)
        {
            Init();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                List<Sys_MenuInfo> lst  = BaseFactory<Sys_Menu>.Instance.GetEntriyList(" 1=1 and PID='"+e.Node.Name+"'");
                
                gcView.DataSource = lst;
                gridView2.BestFitColumns();
            }
        }

        public override void DoImport(IButtonInfo sender)
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog();
                open.Filter= "(excel文件)|*.xls;*.xlsx";
                open.ShowDialog();
                string strPath = open.FileName;
                if (string.IsNullOrEmpty(strPath)) return;
                
                using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("请稍等", "正在导入数据...", new Size(400, 80)))
                {
                    DataTable dt = Lamex.Common.ExecelHelper.ExcelToDataTable(strPath, 1);
                    if (dt.Rows.Count == 0)
                    {
                        XtraMessageBox.Show("没有导入的菜单数据！");
                        return;
                    }
                    foreach (DataRow dr in dt.Rows)
                    {
                        
                        
                        if (dr["LastMenu"].ToString() == "")
                        {
                            //and WinformType='" + dr["WinformType"].ToString() + "'
                            Model.Sys_MenuInfo menu = BaseFactory<Sys_Menu>.Instance.GetEntriyList(" 1=1 and PID='-1'   and WinformId='" + dr["WinformId"].ToString() + "' ").FirstOrDefault();
                            if (menu == null)

                            {
                                Model.Sys_MenuInfo model = new Sys_MenuInfo();
                                model.PID = "-1";
                                model.Name = dr["Name"].ToString();
                                model.WinformId = dr["WinformId"].ToString();
                                model.SortCode = dr["SortCode"].ToString();
                                model.WinformType = dr["DllName"].ToString();
                                model.Image = "";
                                model.SystemType = "001";
                                model.Enabled = true;
                                if (dr["LastMenu"].ToString() == "")
                                    model.MainMenu = dr["DllName"].ToString();
                                model.CreateBy = Loginer.CurrentUser.Account;
                                model.CreateTime = DateTime.Now;
                                model.EngName = dr["EngName"].ToString();
                                model.LastMenu = "";
                                model.WinformName = dr["WinformName"].ToString();
                                model.OpenFormType = dr["OpenFormType"].ToString();
                                if (BaseFactory<Sys_Menu>.Instance.Insert(model))
                                {
                                    Sys_MenuInfo fun = BaseFactory<Sys_Menu>.Instance.GetEntriyList(" 1=1 and PID='" + model.PID + "' and WinformId='" + dr["WinformId"].ToString() + "'").FirstOrDefault();
                                    if (fun != null)
                                    {
                                        string sql = @"INSERT INTO dbo.Sys_Function( ID ,PID ,FunName , FunControlID ,SystemType ,SortCode ,IsVaild ,CreateBy , CreateDate,SysMenu )
                                   VALUES('" + fun.ID + "','" + fun.PID + "','" + fun.Name + "','" + fun.WinformId + "','" + fun.SystemType + "','" + fun.SortCode + "','False','" + Loginer.CurrentUser.Account + "','" + DateTime.Now + "','" + fun.WinformId + "')";
                                        if (BaseFactory<Sys_Function>.Instance.ExecuteNonQuery(sql) > 0)
                                        {
                                            //XtraMessageBox.Show("保存成功！");
                                        }
                                    }
                                }
                            }
                            else
                            {
                                menu.PID = "-1";
                                menu.Name = dr["Name"].ToString();
                                menu.WinformId = dr["WinformId"].ToString();
                                menu.SortCode = dr["SortCode"].ToString();
                                menu.WinformType = dr["WinformType"].ToString();
                                menu.Image = "";
                                menu.SystemType = "001";
                                menu.Enabled = true;
                                if (dr["LastMenu"].ToString() == "")
                                    menu.MainMenu = dr["DllName"].ToString();
                                menu.CreateBy = Loginer.CurrentUser.Account;
                                menu.CreateTime = DateTime.Now;
                                menu.EngName = dr["EngName"].ToString();
                                menu.LastMenu =  "";;
                                menu.WinformName = dr["WinformName"].ToString();
                                menu.OpenFormType = dr["OpenFormType"].ToString();
                                if (BaseFactory<Sys_Menu>.Instance.Update(menu))
                                {
                                    Sys_FunctionInfo function = BaseFactory<Sys_Function>.Instance.GetEntriyList(" 1=1 and PID='" + menu.PID + "' and FunControlID='" + menu.WinformId + "' ").FirstOrDefault();
                                    if (function != null)
                                    {
                                        //function.ID = model.ID;
                                        //function.PID = model.PID;
                                        function.FunName = dr["Name"].ToString();
                                        function.FunControlID = dr["WinformId"].ToString();
                                        function.SystemType = "001";
                                        function.SortCode = dr["SortCode"].ToString();
                                        function.CreateBy = Loginer.CurrentUser.Account;
                                        function.CreateDate = DateTime.Now;
                                        function.SysMenu = dr["DllName"].ToString(); ;
                                       
                                        if (BaseFactory<Sys_Function>.Instance.Update(function))
                                        {
                                            //XtraMessageBox.Show("保存成功！");
                                            //this.Close();
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //int iRank = int.Parse(dr["iRank"].ToString()) - 1;and iRank='" + iRank.ToString() + "'
                            //and WinformType='" + dr["DllName"].ToString() + "' 
                            //and WinformType='" + dr["DllName"].ToString() + "'
                            Sys_MenuInfo sysmenu = BaseFactory<Sys_Menu>.Instance.GetEntriyList(" 1=1  and WinformId='" + dr["LastMenu"].ToString() + "'").FirstOrDefault();
                            if (sysmenu != null)
                            {
                                Sys_MenuInfo mymenu = BaseFactory<Sys_Menu>.Instance.GetEntriyList(" 1=1  and WinformId='" + dr["WinformId"].ToString() + "'").FirstOrDefault();
                                if (mymenu == null)
                                {
                                    Model.Sys_MenuInfo model = new Sys_MenuInfo();
                                    model.PID = sysmenu.ID;
                                    model.Name = dr["Name"].ToString();
                                    model.WinformId = dr["WinformId"].ToString();
                                    model.SortCode = dr["SortCode"].ToString();
                                    model.WinformType = dr["WinformType"].ToString();
                                    model.Image = "";
                                    model.SystemType = "001";
                                    model.Enabled = true;
                                    model.MainMenu = dr["DllName"].ToString();
                                    model.CreateBy = Loginer.CurrentUser.Account;
                                    model.CreateTime = DateTime.Now;
                                    model.EngName = dr["EngName"].ToString();
                                    model.LastMenu = dr["LastMenu"].ToString();
                                    model.WinformName = dr["WinformName"].ToString();
                                    model.OpenFormType = dr["OpenFormType"].ToString();
                                    if (BaseFactory<Sys_Menu>.Instance.Insert(model))
                                    {
                                        //and WinformType='" + dr["DllName"].ToString() + "'
                                        Sys_MenuInfo fun = BaseFactory<Sys_Menu>.Instance.GetEntriyList(" 1=1  and WinformId='" + dr["WinformId"].ToString() + "'").FirstOrDefault();
                                        if (fun != null)
                                        {
                                            string sql = @"INSERT INTO dbo.Sys_Function( ID ,PID ,FunName , FunControlID ,SystemType ,SortCode ,IsVaild ,CreateBy , CreateDate,SysMenu )
                                       VALUES('" + fun.ID + "','" + fun.PID + "','" + fun.Name + "','" + fun.WinformId + "','" + fun.SystemType + "','" + fun.SortCode + "','False','" + Loginer.CurrentUser.Account + "','" + DateTime.Now + "','" + fun.WinformId + "')";
                                            if (BaseFactory<Sys_Function>.Instance.ExecuteNonQuery(sql) > 0)
                                            {
                                                //XtraMessageBox.Show("保存成功！");
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    Model.Sys_MenuInfo model = new Sys_MenuInfo();
                                    //model.ID = mymenu.ID;
                                    //model.PID = mymenu.PID;
                                    mymenu.Name = dr["Name"].ToString();
                                    mymenu.WinformId = dr["WinformId"].ToString();
                                    mymenu.SortCode = dr["SortCode"].ToString();
                                    mymenu.WinformType = dr["WinformType"].ToString();
                                    mymenu.Image = "";
                                    mymenu.SystemType = "001";
                                    mymenu.Enabled = true;
                                    mymenu.MainMenu = dr["DllName"].ToString();
                                    mymenu.CreateBy = Loginer.CurrentUser.Account;
                                    mymenu.CreateTime = DateTime.Now;
                                    mymenu.EngName = dr["EngName"].ToString();
                                    mymenu.LastMenu = dr["LastMenu"].ToString();
                                    mymenu.WinformName = dr["WinformName"].ToString();
                                    mymenu.OpenFormType = dr["OpenFormType"].ToString();
                                    if (BaseFactory<Sys_Menu>.Instance.Update(mymenu))
                                    {
                                        
                                        Sys_FunctionInfo function = BaseFactory<Sys_Function>.Instance.GetEntriyList(" 1=1 and PID='"+ mymenu.PID + "' and FunControlID='" + mymenu.WinformId + "' ").FirstOrDefault();
                                        if (function != null)
                                        {
                                            //function.ID = model.ID;
                                            //function.PID = model.PID;
                                            function.FunName = dr["Name"].ToString();
                                            function.FunControlID = dr["WinformId"].ToString();
                                            function.SystemType = "001";
                                            function.SortCode = dr["SortCode"].ToString();
                                            function.CreateBy = Loginer.CurrentUser.Account;
                                            function.CreateDate = DateTime.Now;
                                            function.SysMenu = dr["DllName"].ToString();;

                                            if (BaseFactory<Sys_Function>.Instance.Update(function))
                                            {
                                                //XtraMessageBox.Show("保存成功！");
                                                //this.Close();
                                            }
                                        }
                                        
                                    }
                                }

                            }

                        }

                    }
                    XtraMessageBox.Show("菜单成功导入！");
                }
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
                return;
            }   
            base.DoImport(sender);
        }
         
    }
}
